import {postReqLog,getReq} from "../http";
import {formatTime} from "../tool";

const GET_CATEGORY = 'GET_CATEGORY'
const ERROR_MSG = 'ERROR_MSG'
const SET_CATEGORY = 'SET_CATEGORY'
const GET_CATEGORY_CHILDREN ='GET_CATEGORY_CHILDREN'
const ADD_CATEGORY = 'ADD_CATEGORY'
const initState={
    data:[],
    msg:null,
    updateSuccess:false,
    addSuccess:false,
    data_children:[]
}
// reducer
export function category(state=initState, action){
    switch(action.type){
        case GET_CATEGORY:
            return {...state,data:action.payload}
        case GET_CATEGORY_CHILDREN:
            return {...state,data_children:action.payload}
        case SET_CATEGORY:
            return {...state,updateSuccess:action.updateSuccess}
        case ADD_CATEGORY:
            return {...state,addSuccess:action.addSuccess}
        case ERROR_MSG:
            return {...state,msg:action.msg}
        default:
            return state
    }
}

function errorMsg(msg){
    return { msg, type:ERROR_MSG }
}
function updateSuccess(updateSuccess,id){
    return { updateSuccess ,type:SET_CATEGORY }
}
export function getCategory(categoryId){
    return async dispatch=>{
        let res = await getReq('/api/getCategory',{categoryId})
        if(res.data){
            dispatch(success(res.data))
        }else {
            dispatch(errorMsg(res.msg))
        }
    }
}
export function updateCategoryName(categoryId,categoryName){
    return async dispatch=>{
        let res = await getReq('/api/updateCategoryName',{categoryId,categoryName})
        if(res.data){
            dispatch(updateSuccess(true,categoryId))

        }else {
            dispatch(errorMsg(res.msg))
        }
    }
}

export function getChildrenCategory(categoryId){
    return async dispatch=>{
        let res = await getReq('/api/getCategory',{categoryId})
        if(res.data){

            dispatch(success1(res.data))
        }else {
            dispatch(errorMsg(res.msg))
        }
    }
}

function addCategorySuccess(addSuccess) {
    return { addSuccess ,type:ADD_CATEGORY }
}
export function addCategory(data){
    return async dispatch=>{
        let res = await getReq('/api/addCategory',data)
        if(res.data){
            dispatch(addCategorySuccess(true))
        }else {
            dispatch(errorMsg(res.msg))
        }
    }
}


function success1(obj) {
    let newList = []
    for (let i = 0; i < obj.length; i++) {
        let item = obj[i]
        newList.push({...item, key: i + 1})
    }

    return {type: GET_CATEGORY_CHILDREN, payload: newList}
}

function success(obj) {
    let newList = []
    for (let i = 0; i < obj.length; i++) {
        let item = obj[i]
        newList.push({...item, key: i + 1})
    }
    return {type: GET_CATEGORY, payload: newList}
}




